﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GenerationCode.CSClasses
{
    class ObjectUtil
    {

        private Utils.Table table;
        private string projectName;
        private string coder;
        private string email;
        private string objectClass;
        private bool genFunctionToControl;
        private  string deleteCache =string.Empty;           
        public ObjectUtil(Utils.Table tb, string projectName, string coder, string email, bool genFunctionToControl)
        {
            if (tb.IsCacheData)
                deleteCache = string.Format("BizObject.PurgeCacheItems({0}{1}{2});\n", '"', tb.Name, '"');          
            this.table = tb;
            this.projectName = projectName;
            this.coder = coder;
            this.email = email;
            this.genFunctionToControl = genFunctionToControl;
        }

        //set header
        private string SetHeader()
        {
            string header = string.Format(@"
            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using {0};
            using {1};

            namespace {2}
            {3}
                   /// <summary>
                    /// Define {4}Util class. This class user for BussinessLayer.
    
                /// </summary>
              public class {4}Util {3}",Utils.Utility.BusinessObjectNamespace,Utils.Utility.DataAccessNamespace,Utils.Utility.BusinessLogicNamespace,"{", table.Name);
            return header;
        }
        //set comon method
        private string SetComon()
        {
           
            string comon = CommonInsert() + CommonUpdate() + CommonGetAll(false) + CommonSearchSomeConditionGetTotalRow();     
            string key = "{0}" + this.table.Name + "_GetToControl_{1}";
            key = string.Format(key, '"', '"');
            string keyCount = string.Empty;
            int i = 0;
            string strDaoParamater=string.Empty;
            foreach (Utils.Column col in table.Columns)
            {
                strDaoParamater += "t." + Utils.Utility.ConvertToPropertyName(col.Name) + ",";                    
                    keyCount += "{" + i.ToString() + "}_";
                    i++;
            }
            strDaoParamater = strDaoParamater.Substring(0, strDaoParamater.Length - 1);
            keyCount = keyCount.Substring(0, keyCount.Length - 1);
            keyCount = "\"" + keyCount + "\"";
            key = key + " + string.Format({3}," + strDaoParamater + ")";
            string function = string.Empty;          
            if (genFunctionToControl)
            {
                if (!this.table.IsCacheData)
                {
                    function += "\r\n";
                    function += string.Format(@"                   
                  
                       /// <summary>
                    /// Get List object to fill control(combobox, listbox,...).
                    /// </summary>
                    /// <param name=""t"">Condition for search.</param>
                    /// <returns>List {0}ToControl object.</returns>
                    public static List<{0}ToControl> Get{0}ToControl({0}ToControlCondition t)
                    {1}
                      return {0}Dao.Get{0}ToControl(t);
                    {2}       
                  
                  
                       ", table.Name, "{", "}");
                }
                else
                {
                    string s = @"
                  /// <summary>
                    /// Get List object to fill control(combobox, listbox,...).
                    /// </summary>
                    /// <param name=""t"">Condition for search.</param>
                    /// <returns>List {0}ToControl object.</returns>
                    public static List<{0}ToControl> Get{0}ToControl({0}ToControlCondition t)
                    {1}
                       List<{0}ToControl> obj = null;
                        string key =" + key + @";
                        if (BizObject.Cache[key] != null)
                        {1}
                            obj = (List<{0}ToControl>)BizObject.Cache[key];
                        {2}
                        else
                        {1}
                            obj={0}Dao.Get{0}ToControl(t);                            
                            BizObject.CacheData(key, obj);
                        {2}
                        return obj;
                     {2}
                    ";
                    function = string.Format(s, table.Name, '{', '}', keyCount);                    
                }
                comon += function;
            }
            return comon;
        }
        //set footer
        private string footer()
        {
            return "} }";
        }
        public string GetObject()
        {
            return this.SetHeader() + this.SetComon() + CommonGet(false) +  CommonDelete() + this.footer();
        }
        private bool inKeyList(string p)
        {

            foreach (object col in table.KeyList)
            {
                if (col.ToString().Trim() == p.Trim())
                    return true;

            }
            return false;
        }
        private string CommonGet(bool byLanguage)
        {
            
            string key = "{0}" + this.table.Name + "_Get_{1}";
            if(byLanguage)
                key = "{0}" + this.table.Name + "_Get" + Utils.Utility.FunctionByLanguageName + "_{1}";
            key = string.Format(key, '"', '"');
            string keyCount = string.Empty;
            string commentParamater = string.Empty;
            string comment = string.Empty;
            string strPkParamater = string.Empty;
            string strDaoParamater = string.Empty;
            int i=0;
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    strPkParamater = strPkParamater + col.DataType + " " + col.Name + ",";
                    strDaoParamater += col.Name + ",";
                    commentParamater += "/// <param name={0}" + col.Name + "{0} >This is primary key.</param>\r\n";
                    keyCount += "{" + i.ToString() + "}_";                    
                    i++;
                }
            }
            commentParamater = string.Format(commentParamater, '"');
            comment = "\r\n/// <summary>\r\n";
            comment += "/// Get a " + table.Name + " data object by primary key. \r\n";
            comment += "/// </summary>\r\n";
            comment += commentParamater ;
            comment += "/// <returns>A " + table.Name + " object.</returns>\r\n";
            strPkParamater = strPkParamater.Substring(0, strPkParamater.Length - 1);
            strDaoParamater = strDaoParamater.Substring(0, strDaoParamater.Length - 1);
            keyCount = keyCount.Substring(0, keyCount.Length - 1);
            keyCount="\"" + keyCount + "\"";
            key =key +" + string.Format({3}," + strDaoParamater + ")";        
            string function = string.Empty;
            if (table.IsCacheData)
            {
                string s = string.Empty;
                if (!byLanguage)
                {
                    s = @"
                     public static {0} Get(" + strPkParamater + @")                    
                    {1}
                       {0} obj = null;
                        string key =" + key + @";
                        if (BizObject.Cache[key] != null)
                        {1}
                            obj = ({0})BizObject.Cache[key];
                        {2}
                        else
                        {1}
                            obj = {0}Dao.Get(" + strDaoParamater + @");
                            BizObject.CacheData(key, obj);
                        {2}
                        return obj;
                     {2}
                    ";
                    function = comment + string.Format(s, table.Name, '{', '}', keyCount);
                }
                else
                {
                    if (!table.IsMultilanguage)
                        return string.Empty;
                    s = @"
                     public static {0} Get" + Utils.Utility.FunctionByLanguageName + "(" + strPkParamater + "," + Utils.Utility.LanguageIDFieldDataType + " " + Utils.Utility.LanguageIDField  + @")                    
                    {1}
                       {0} obj = null;
                        string key =" + key + @";
                        if (BizObject.Cache[key] != null)
                        {1}
                            obj = ({0})BizObject.Cache[key];
                        {2}
                        else
                        {1}
                            obj = {0}Dao.Get" + Utils.Utility.FunctionByLanguageName + "(" + strDaoParamater + @"," + Utils.Utility.LanguageIDField + @");
                            BizObject.CacheData(key, obj);
                        {2}
                        return obj;
                     {2}
                    ";
                    function = comment + string.Format(s, table.Name, '{', '}', keyCount);
                }
                return function;
            }
            else
            {
                if (!byLanguage)
                {
                    function = comment + string.Format(@"
                    public static {0} Get(" + strPkParamater + @")
                    {1}
                      return {0}Dao.Get(" + strDaoParamater + @");
                    {2}", table.Name, '{', '}');
                }
                else
                {
                    if (!table.IsMultilanguage)
                        return string.Empty;
                    function = comment + string.Format(@"
                    public static {0} Get{3}(" + strPkParamater + @",{4} {5})
                    {1}
                      return {0}Dao.Get{3}(" + strDaoParamater + @");
                    {2}", table.Name, '{', '}',Utils.Utility.FunctionByLanguageName,Utils.Utility.LanguageIDFieldDataType,Utils.Utility.LanguageIDField);
                }
            }
            return function;

        }
        private string CommonDelete()
        {
            string comment = string.Empty;
            string commentPara = string.Empty;
            string strPkParamater = string.Empty;
            string strDaoParamater = string.Empty;
            foreach (Utils.Column col in table.Columns)
            {
                if (col.IsPK || inKeyList(col.Name))
                {
                    strPkParamater = strPkParamater + col.DataType + " " + col.Name + ",";
                    strDaoParamater += col.Name + ",";
                    commentPara += "/// <param name={0}" + col.Name + "{0} >This is primary key.</param>\r\n";

                }
            }
            commentPara = string.Format(commentPara, '"');
            comment = "\r\n/// <summary>\r\n";
            comment += "/// This function to Delete " + table.Name + " object by primary key.\r\n";
            comment += "/// </summary>\r\n";
            comment += commentPara ;
            comment += "/// <returns>If succesful return True else  return False.</returns>\r\n";
            strPkParamater = strPkParamater.Substring(0, strPkParamater.Length - 1);
            strDaoParamater = strDaoParamater.Substring(0, strDaoParamater.Length - 1);
            string function = comment + string.Format(@"
                    public static bool Delete(" + strPkParamater + @")
                    {1}
                         " + deleteCache + @"
                      return {0}Dao.Delete(" + strDaoParamater + @");
                    {2}", table.Name, '{', '}');
            return function;

        }
        private string CommonInsert()
        {
           
            string comon = string.Empty;
            comon = string.Format(@"
                    /// <summary>
                    /// Define function Insert for {0} Object.
                    /// </summary>
                    /// <param name=""t"">object data need Insert.</param>
                    /// <returns>
                    ///    True: if insert successfull.
                    ///    False: if insert error.
                    ///</returns>
                    public static bool Insert({0} t)
                    {1}
                        " + deleteCache  + @"
                      return {0}Dao.Insert(t);
                    {2}", table.Name, "{", "}");
            return comon;
        }
        private string CommonUpdate()
        {
             string comon = string.Empty;
            comon = string.Format(@"
                    /// <summary>
                    /// Define function Update for {0} Object.
                    /// </summary>
                    /// <param name=""t"">project data need updated.</param>
                    /// <returns>
                    ///    True: if update successful.
                    ///    False: if update Error.
                    ///</returns>
                    public static bool Update( {0} t )
                    {1}
                        " + deleteCache + @"
                      return {0}Dao.Update( t );
                    {2}", table.Name, "{", "}");
            return comon;   

        }
        private string CommonGetAll(bool byLanguage)
        {
            if (this.table.IsCacheData)
            {
                string cache = string.Empty;
                if (!byLanguage)
                {
                    cache = @"
                    /// <summary>
                    /// Get All {0} object from table {0}.
                    /// </summary>
                    /// <returns>List {0} object.</returns>
                    public static List<{0}> GetAll()
                    {1}     
                        List<{0}> obj = null;
                        string key = {3}{0}_GetAll{4};
                        if (BizObject.Cache[key] != null)
                        {1}
                            obj = (List<{0}>)BizObject.Cache[key];
                        {2}
                        else
                        {1}
                            obj = {0}Dao.GetAll();
                            BizObject.CacheData(key, obj);
                        {2}
                        return obj;
                    {2}";
                    return string.Format(cache, table.Name, "{", "}", '"', '"');
                }
                else
                {
                    if (!table.IsMultilanguage)
                        return string.Empty;
                    cache = @"
                    /// <summary>
                    /// Get All {0} object from table {0}.
                    /// </summary>
                    /// <returns>List {0} object.</returns>
                    public static List<{0}> GetAll" + Utils.Utility.FunctionByLanguageName + @"(" + Utils.Utility.LanguageIDFieldDataType + " " + Utils.Utility.LanguageIDField  + @")
                    {1}     
                        List<{0}> obj = null;
                        string key = {3}{0}_GetAll_" + Utils.Utility.FunctionByLanguageName  + @"{4};
                        if (BizObject.Cache[key] != null)
                        {1}
                            obj = (List<{0}>)BizObject.Cache[key];
                        {2}
                        else
                        {1}
                            obj = {0}Dao.GetAll" + Utils.Utility.FunctionByLanguageName + @"(" + Utils.Utility.LanguageIDField + @");
                            BizObject.CacheData(key, obj);
                        {2}
                        return obj;
                    {2}";
                    return string.Format(cache, table.Name, "{", "}", '"', '"');
                }
            }
            else
            {
                string cache=string.Empty;
                if(!byLanguage)
                {
                    cache=@"
                    /// <summary>
                    /// Get All {0} object from table {0}.
                    /// </summary>
                    /// <returns>List {0} object.</returns>
                    public static List<{0}> GetAll()
                    {1}     
                        return {0}Dao.GetAll();
                    {2}";            
                return string.Format(cache, table.Name, "{", "}");
                }
                else
                {
                    if (!table.IsMultilanguage)
                        return string.Empty;
                    cache=@"
                    /// <summary>
                    /// Get All {0} object from table {0}.
                    /// </summary>
                    /// <returns>List {0} object.</returns>
                    public static List<{0}> GetAll{3}({4} {5})
                    {1}     
                        return {0}Dao.GetAll({5});
                    {2}";            
                return string.Format(cache, table.Name, "{", "}",Utils.Utility.FunctionByLanguageName,Utils.Utility.LanguageIDFieldDataType,Utils.Utility.LanguageIDField);
                }
            }
        }
       
        private string CommonSearchSomeConditionGetTotalRow()
        {
            if (table.Name.Contains(Utils.Utility.MultilanguageTableName))
            {
                return string.Empty;
            }
            string comon = string.Empty;
            comon = string.Format(@"
                    /// <summary>
                    /// Search {0} object in table {0}.
                    /// </summary>
                    /// <param name=""t"">Condition for Search.</param>

                    /// <returns>List {0} objects.</returns>

                     public static List<{0}> Search{0}({0} t,string " + Utils.Utility.LanguageIDField + @")
                {1}
                        return  {0}Dao.Search{0}(t," + Utils.Utility.LanguageIDField + @");
                {2}", table.Name, "{", "}");
            return comon;
        }    

    }
}
